import { PlusOutlined } from '@ant-design/icons';
import { ProForm } from '@ant-design/pro-components';
import {
  Col,
  Form,
  Image,
  Input,
  Radio,
  Row,
  Space,
  Upload,
  message,
} from 'antd';
import { useEffect, useRef, useState } from 'react';
import { history } from 'umi';
import { isLoginIdExisted } from '../../../services/admin';
export default function AdminForm(props) {
  // 当前组件是抽离出来用来添加和编辑的表单
  console.log(props);
  const formRef = useRef();
  const type = props.type;
  const initData = props.initData;
  const [imageUrl, setimageUrl] = useState('');
  let oldId;
  if (props.type === 'edit') {
    oldId = props.initData.loginId;
  }
  // console.log(PlusOutlined)
  function handlePmsChange() {}
  function handleFromFinish(res) {
    // 判断当前是否选择了图片
    let submitObj = { ...formRef.current.getFieldsFormatValue() };
    if (imageUrl !== '') {
      // 需要提交头像信息
      submitObj.avatar = imageUrl;
    }
    console.log('提交submitObj', submitObj);
    // 对编辑后的进行特殊性处理
    if (props.type === 'edit') {
      submitObj = Object.assign({}, initData, submitObj);
    }
    props.submit(submitObj);
    const title = type === 'add' ? '新增' : '编辑';
    message.success(`${title}成功`);
    // 跳转列表
    history.push('/admin/adminList');
    setimageUrl('');
  }
  function handleAvatarChange(data) {
    const { file, fileList, event } = data;
    if (file.status === 'done' && file.response.data) {
      // 拿到要上传的头像地址,设置图片
      setimageUrl(file.response.data);
    }
  }
  useEffect(() => {
    console.log('设置初始值');
    formRef.current.setFieldsValue(props.initData);
  }, [props.initData]);
  function validateLoginId(val) {
    // 请求验证当前账号是否可用
    return isLoginIdExisted(val).then((res) => {
      // console.log('是否可用',res)
      // 注意如果进行编辑表单的时候是账号名字是可以和自己之前的名字相同
      if (props.type === 'edit' && oldId === val) {
        return Promise.resolve();
      }
      if (res.data) {
        return Promise.reject('当前账号已经被注册,请更换账号');
      }
      return Promise.resolve();
    });
  }
  // function test(){
  //     history.push('/admin/adminList');
  // }

  const uploadButton = (
    <div>
      {<PlusOutlined></PlusOutlined>}
      <div
        style={{
          marginTop: 8,
        }}
      >
        Upload
      </div>
    </div>
  );
  return (
    <ProForm
      layout="horizontal"
      labelCol={{
        span: 6,
      }}
      wrapperCol={{
        span: 16,
      }}
      formRef={formRef}
      onFinish={handleFromFinish}
      // setFieldValue={initData}
      submitter={{
        render: (props, doms) => {
          return (
            <Row>
              <Col span={14} offset={4}>
                <Space>{doms}</Space>
              </Col>
            </Row>
          );
        },
      }}
    >
      <Form.Item
        label="管理员账号"
        name="loginId"
        validateFirst={true}
        validateTrigger="onBlur"
        rules={[
          {
            required: true,
            message: '请输入登录账号',
          },
          {
            max: 10,
            min: 4,
            message: '长度在4-10之间',
          },
          ({ getFieldValue }) => ({
            validator(_, value) {
              return validateLoginId(value);
            },
          }),
        ]}
      >
        <Input />
      </Form.Item>

      <Form.Item
        label="管理员密码"
        name="loginPwd"
        rules={
          type === 'edit'
            ? [
                {
                  required: true,
                  message: '请输入登录密码',
                },
              ]
            : null
        }
      >
        <Input.Password />
      </Form.Item>
      <Form.Item
        label="管理员昵称"
        name="nickname"
        rules={
          type === 'edit'
            ? [
                {
                  required: true,
                  message: '请输入昵称',
                },
              ]
            : null
        }
      >
        <Input />
      </Form.Item>
      <Form.Item
        label="权限选择"
        name="permission"
        rules={[
          {
            required: true,
            message: '请选择权限',
          },
        ]}
      >
        <Radio.Group onChange={handlePmsChange}>
          <Radio value={1}>超级管理员</Radio>
          <Radio value={2}>普通管理员</Radio>
        </Radio.Group>
      </Form.Item>
      {props.type === 'edit' ? (
        <Form.Item label="当前头像">
          <Image width={100} src={props.initData.avatar} />
        </Form.Item>
      ) : null}
      <Form.Item label="上传图片">
        <Upload
          showUploadList={false}
          onChange={handleAvatarChange}
          className="avatar-uploader"
          listType="picture-card"
          action="/api/upload"
          maxCount={1}
        >
          {imageUrl !== '' ? (
            <img
              src={imageUrl}
              alt="avatar"
              style={{
                width: '100%',
              }}
            />
          ) : (
            uploadButton
          )}
        </Upload>
        {/* action="https://run.mocky.io/v3/435e224c-44fb-4773-9faf-380c5e6a2188" */}
      </Form.Item>
    </ProForm>
  );
}
